package com.ruoyi.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.base.domain.SyType;
import com.ruoyi.base.domain.vo.SyYjDetailVo;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.helper.DataBaseHelper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.TreeBuildUtils;
import com.ruoyi.common.utils.redis.CacheUtils;
import com.ruoyi.sycs.service.ISycsDataDetailGjService;
import com.ruoyi.sycs.service.ISycsDataDetailService;
import com.ruoyi.sycs.service.ISycsDataDetailSyService;
import com.ruoyi.sycs.service.ISycsDataDetailWaterService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import liquibase.pro.packaged.P;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.base.domain.bo.SyYjBo;
import com.ruoyi.base.domain.vo.SyYjVo;
import com.ruoyi.base.domain.SyYj;
import com.ruoyi.base.mapper.SyYjMapper;
import com.ruoyi.base.service.ISyYjService;

import java.util.*;

/**
 * 试验依据Service业务层处理
 *
 * @author zyb
 * @date 2024-04-12
 */
@RequiredArgsConstructor
@Service
public class SyYjServiceImpl implements ISyYjService {

    private final SyYjMapper baseMapper;

    private final ISysDictTypeService iSysDictTypeService;

    private final ISycsDataDetailService iSycsDataDetailService;
    private final ISycsDataDetailWaterService iSycsDataDetailWaterService;
    private final ISycsDataDetailSyService iSycsDataDetailSyService;
    private final ISycsDataDetailGjService iSycsDataDetailGjService;

    /**
     * 查询试验依据
     */
    @Override
    public SyYjVo queryById(Long syYjId){
        return baseMapper.selectVoById(syYjId);
    }


    /**
     * 查询试验依据列表
     */
    @Override
    public List<SyYjVo> queryList(SyYjBo bo) {
        LambdaQueryWrapper<SyYj> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SyYj> buildQueryWrapper(SyYjBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SyYj> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getSyYjName()), SyYj::getSyYjName, bo.getSyYjName());
        lqw.eq(StringUtils.isNotBlank(bo.getYjDetailType()), SyYj::getYjDetailType, bo.getYjDetailType());
        return lqw;
    }

    /**
     * 新增试验依据
     */
    @Override
    public Boolean insertByBo(SyYjBo bo) {
        SyYj add = BeanUtil.toBean(bo, SyYj.class);
        validEntityBeforeSave(add);
        Integer sort = getMaxSortByParentId(bo.getParentId());
        if (ObjectUtils.isEmpty(sort)) {
            sort = 0;
        }
        add.setDelFlag("0");
        add.setCreateBy(LoginHelper.getUsername());
        add.setCreateTime(new Date());
        add.setSort(sort + 1);
        // 维护排序
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setSyYjId(add.getSyYjId());
        }
        return flag;
    }

    /**
     * 修改试验依据
     */
    @Override
    public Boolean updateByBo(SyYjBo bo) {
        SyYj update = BeanUtil.toBean(bo, SyYj.class);
        validEntityBeforeSave(update);
        update.setUpdateBy(LoginHelper.getUsername());
        update.setUpdateTime(new Date());
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SyYj entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除试验依据
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询依据树结构信息
     *
     * @param yj 依据信息
     * @return 依据树信息集合
     */
    @Override
    public List<Tree<Long>> selectYjTreeList(SyYj yj) {
        List<SyYj> yjs = this.selectYjList(yj);
        return buildYjTreeSelect(yjs);
    }

    /**
     * 获取依据子集/明细
     *
     * @param yj
     * @param pageQuery
     * @return
     */
    @Override
    public SyYjDetailVo listByYjId(SyYj yj, PageQuery pageQuery) {
        SyYjDetailVo data = new SyYjDetailVo();
        if (ObjectUtils.isEmpty(yj.getSyYjId())) {
            data.setType("");
            data.setPage(new Page());
            return data;
        }
//        List<SysDictData> dictData = iSysDictTypeService.selectDictDataByType("syyj_detail_type");
        SyYj entity = baseMapper.selectById(yj.getSyYjId());
        // 点击第一层
        if (yj.getSyYjId() == 281757153833L) {
            // 水密
            Page page = iSycsDataDetailWaterService.listBySyTypeId(yj.getSyYjId(), pageQuery);
            data.setPage(page);
            data.setType("detailWater");
            return data;
        }
        else if (yj.getSyYjId() == 2143842384353L) {
            // 水银
            Page page = iSycsDataDetailSyService.listBySyTypeId(yj.getSyYjId(), pageQuery);
            data.setPage(page);
            data.setType("detailSy");
            return data;
        }
        else if (yj.getSyYjId() == 1818216586924834817L) {
            // 钢筋
            Page page = iSycsDataDetailGjService.listBySyTypeId(yj.getSyYjId(), pageQuery);
            data.setPage(page);
            data.setType("detailGj");
            return data;
        }
        else if (entity.getParentId() == 0) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("del_flag", "0");
            wrapper.eq("parent_id", yj.getSyYjId());
            Page page = baseMapper.selectPage(pageQuery.build(), wrapper);
            data.setPage(page);
            data.setType("leaf2");
            return data;
        }
        // 点击第二层
        else if (entity.getParentId() != 0 && entity.getYjDetailType() == null) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("del_flag", "0");
            wrapper.eq("parent_id", yj.getSyYjId());
            Page page = baseMapper.selectPage(pageQuery.build(), wrapper);
            data.setPage(page);
            data.setType("leaf3");
            return data;
        }
        // 点击第三层
        else {
            Page page = iSycsDataDetailService.listBySyTypeId(yj.getSyYjId(), pageQuery);
            data.setPage(page);
            data.setType("detail");
            return data;
        }
    }

    /**
     * 根据上级id获取最大排序
     *
     * @param parentId
     * @return
     */
    @Override
    public Integer getMaxSortByParentId(Long parentId) {
        return baseMapper.getMaxSortByParentId(parentId);
    }


    public List<SyYj> selectYjList(SyYj yj) {
        LambdaQueryWrapper<SyYj> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SyYj::getDelFlag, "0")
            .eq(ObjectUtil.isNotNull(yj.getSyYjId()), SyYj::getSyYjId, yj.getSyYjId())
            .eq(ObjectUtil.isNotNull(yj.getParentId()), SyYj::getParentId, yj.getParentId())
            .like(StringUtils.isNotBlank(yj.getSyYjName()), SyYj::getSyYjName, yj.getSyYjName())
            .orderByAsc(SyYj::getParentId)
            .orderByAsc(SyYj::getSort);
        return baseMapper.selectList(lqw);
    }

    public List<Tree<Long>> buildYjTreeSelect(List<SyYj> yjs) {
        if (CollUtil.isEmpty(yjs)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(yjs, (yj, tree) ->
            tree.setId(yj.getSyYjId())
                .setParentId(yj.getParentId())
                .setName(yj.getSyYjName())
                .setWeight(yj.getSort()));
    }

}
